<?php

require_once PATH_CLASS.'/saison.class.php';
require_once PATH_CLASS.'/image.class.php';
require_once PATH_CLASS.'/my.UploadHandler.class.php';

class match extends table {

  public static  $CLASS_NAME  = 'match';
  public static  $TABLE_NAME  = 't_matchs';
  public static  $PRIMARY_KEY = 'match_id';  
  
  var $match_id;
  var $match_saison_id;
  var $match_date;
  var $match_compet_id;
  var $match_equipe_A;
  var $match_equipe_B;
  var $match_logistique;
  var $match_affichage;
  var $match_lieu_id;
  var $match_score_A;
  var $match_score_B;
  var $match_MC;
  var $match_DJ;
  var $match_valide;
  var $match_type_id;
  var $match_type_lib;
  var $match_has_image;
  
  public static function getTableName() {
    return self::$TABLE_NAME;
  }

  public static function getClassName() {
    return self::$CLASS_NAME;
  }

  public static function getPrimaryKey() {
    return self::$PRIMARY_KEY;
  }
  
  public function update($fieldNames = '*') {
    $ret = parent::update($fieldNames, self::getClassName());
    return $ret;
  }
  
  public static function getRanking($saison_id,$type){
    $db     = parent::getDb();
    
    if(is_null($saison_id) || empty($saison_id) ) $saison_id=saison::getCurrentId();
    $saison = saison::getSaison($saison_id);
    
    $point = new stdClass();
    $point->gagne   = (isset($saison->point_gagnant)  ? $saison->point_gagnant  :2);
    $point->egalite = (isset($saison->point_egalite)  ? $saison->point_egalite  :1);
    $point->perdu   = (isset($saison->point_perdu)    ? $saison->point_perdu    :0);
    
  
    if(empty($type)) $type=saison::CHAMPIONNAT;
    
    switch($type){
      case saison::CHAMPIONNAT:
        $compet_id = 1;
        break;
      case saison::JOUTELIBRE:
        $compet_id = 4;
        break;
    }
    

    $sql=sprintf("select count(*) from t_matchs as t_m 
    inner join t_equipes as t_e on t_e.equipe_id = t_m.match_equipe_a or t_e.equipe_id = t_m.match_equipe_b
    inner join t_saisons as t_s on t_s.saison_id=t_m.match_saison_id
    inner join t_liens_es as t_les on t_les.equipe_id=t_e.equipe_id and t_les.saison_id=t_s.saison_id
    where t_s.saison_id='%d' and t_les.saison_type='%s'
      and (t_m.match_score_A<>0 or t_m.match_score_B<>0)
    and t_m.match_compet_id=%d and t_m.match_type_id not in (5,6)",$saison->saison_id,$type,$compet_id);

    $countMatch = $db->Count($sql);

    $sql=sprintf("select t_e.equipe_id from t_matchs as t_m 
    inner join t_equipes as t_e on t_e.equipe_id = t_m.match_equipe_a or t_e.equipe_id = t_m.match_equipe_b 
    inner join t_saisons as t_s on t_s.saison_id=t_m.match_saison_id 
    inner join t_liens_es as t_les on t_les.equipe_id=t_e.equipe_id and t_les.saison_id=t_s.saison_id 
    where t_s.saison_id='%d' and t_les.saison_type='%s' and t_m.match_compet_id=%d and t_m.match_type_id not in (5,6) 
    group by t_e.equipe_id",$saison->saison_id,$type,$compet_id);

    $countEquipe = count($db->SelectAll($sql));

    $sql=sprintf("SELECT t_e.*
    FROM t_equipes AS t_e
    INNER JOIN t_liens_es AS t_les ON t_e.equipe_id = t_les.equipe_id
    WHERE t_les.saison_id=%d and t_les.saison_type='%s'",$saison->saison_id,$type);

    $equipes = $db->SelectAll($sql);
    
    if(empty($equipes)){
      $equipes = array();
    }

    $sql=sprintf("select match_equipe_A,match_equipe_B,match_score_A,match_score_B,match_date from t_matchs as t_m 
    inner join t_equipes as t_e on t_e.equipe_id = t_m.match_equipe_a
    inner join t_saisons as t_s on t_s.saison_id=t_m.match_saison_id
    inner join t_liens_es as t_les on t_les.equipe_id=t_e.equipe_id and t_les.saison_id=t_s.saison_id
    where t_s.saison_id='%d' and t_les.saison_type='%s'
    and t_m.match_compet_id=%d and t_m.match_type_id not in (5,6) order by match_date",$saison->saison_id,$type,$compet_id);

    $matchs         = $db->SelectAllBy($sql,'match_equipe_A,match_equipe_B'); 
    $matchsParDate  = $db->SelectAll($sql);

    /**/
    $sql=sprintf('select t_e.equipe_id,
    sum(
      if(match_equipe_A=t_e.equipe_id and match_score_A>match_score_B and match_date<=now(),%3$d,
        if(match_equipe_B=t_e.equipe_id and match_score_B>match_score_A and match_date<=now(),%3$d,
          if(match_score_A>0 and match_score_B=match_score_A and match_date<=now(),%4$d,%5$d)
        )
      )
    ) as points,
    sum(if(match_date<=now(),1,0)) as joues,
    sum(
      if(match_equipe_A=t_e.equipe_id and match_score_A>match_score_B and match_date<=now(),1,
        if(match_equipe_B=t_e.equipe_id and match_score_B>match_score_A and match_date<=now(),1,0)
      )
    ) as gagnes,
    sum(
      if(match_score_A=match_score_B and match_date<=now() and match_score_A>0,1,0)
    ) as egalites,
    sum(
      if(match_score_A=0 and match_score_B=0,0,
        if(match_equipe_A=t_e.equipe_id and match_score_A<match_score_B and match_date<=now(),1,
          if(match_equipe_B=t_e.equipe_id and match_score_B<match_score_A and match_date<=now(),1,0)
        )
      )
    ) as perdus,
    sum(
      If(match_equipe_A=t_e.equipe_id,match_score_A,match_score_B)
    ) as pp,
    sum(
      If(match_equipe_A=t_e.equipe_id,match_score_B,match_score_A)
    ) as pc,
    sum(
      If(match_equipe_A=t_e.equipe_id,match_score_A,match_score_B)
    )-
    sum(
      If(match_equipe_A=t_e.equipe_id,match_score_B,match_score_A)
    ) as diff
    from t_equipes as t_e
    inner join t_matchs as t_m on t_e.equipe_id = match_equipe_a or t_e.equipe_id=match_equipe_b
    inner join t_saisons as t_s on t_s.saison_id=t_m.match_saison_id
    inner join t_liens_es as t_les on t_les.equipe_id=t_e.equipe_id and t_les.saison_id=t_s.saison_id
    where t_s.saison_id=%1$d and t_les.saison_type="%2$s"
    and t_m.match_compet_id=%6$d and t_m.match_type_id not in (5,6)
    group by t_e.equipe_id order by points desc,diff desc, joues asc,equipe_nom',$saison->saison_id,$type,$point->gagne,$point->egalite,$point->perdu,$compet_id);


    $resultattb = $db->SelectAll($sql);

      /*
      Si jamais deux �quipes sont a �galit� de points, et de diff on doit comparer le match
      de r�f�rence entre les deux �quipes
    */
    $warn           = false;
    
      for($i=0;$i<count($resultattb);$i++){
       $res1 = $resultattb[$i];
       
       if(!isset($resultattb[$i+1])) 
         break;
       
       $res2 = $resultattb[$i+1];

       if($res1['points']==$res2['points'] && $res1['joues']==$res2['joues'] && $res1['diff']==$res2['diff']){
         // On cherche le résultat du match entre les deux équipes
         if(isset($matchs[$res1['equipe_id']][$res2['equipe_id']])){
           $match = $matchs[$res1['equipe_id']][$res2['equipe_id']];
         }
         else{
           $match = $matchs[$res2['equipe_id']][$res1['equipe_id']];
         }

        if($match['match_score_A']  < $match['match_score_B']){
          $resultattb[$i]   = $res2;
          $resultattb[$i+1] = $res1;
          $warn				= true;
        }
       }
      }
      // On determine si la pool est finie
      $poolFinie=false;
      // Si on a des résultats pour toutes les équipes
      if(count($resultattb)==$countEquipe){
        $poolFinie  = true;      
        $joue       = $resultattb[0]['joues'];
        // Ont-elles toutes le même nombre de matchs joués?
        foreach($resultattb as $res){
          // Non la pool n'est pas terminée
          if($res['joues']!=$joue) $poolFinie=false;
        }
      }

      //$smarty->assign('resultattb',$resultattb);
      
    function updateMatchTeams($id,$equipe_A,$equipe_B){
      $ret=false;
      $match = match::getMatch($id);
      if($match){
        $match->match_equipe_A = $equipe_A; 
        $match->match_equipe_B = $equipe_B;
        $ret = $match->update(array('match_equipe_A','match_equipe_B'));
      }
      return($ret);
    }

    /**/
    $sql=sprintf("select t_m.match_id,t_m.match_date,t_m.match_equipe_A,t_m.match_equipe_B,t_m.match_score_A,t_m.match_score_B,t_m.match_equipe_A as teamA
    from t_matchs as t_m
    left join t_equipes as t_e on t_e.equipe_id = match_equipe_a or t_e.equipe_id=match_equipe_b
    inner join t_saisons as t_s on t_s.saison_id=t_m.match_saison_id
    left join t_liens_es as t_les on t_les.equipe_id=t_e.equipe_id and t_les.saison_id=t_s.saison_id
    where t_s.saison_id='%d' and IFNULL(t_les.saison_type,'%2\$s')='%2\$s' and t_m.match_type_id in (5,6)
    group by t_m.match_id order by t_m.match_type_id,t_m.match_date",$saison->saison_id,$type);	
    /**/	

      $demies   = $db->SelectAll($sql);
      $demiesOk = true;

      if((empty($demies[0]) || $demies[0]['teamA']==0) && !empty($resultattb[0]) && !empty($resultattb[3]) ){
          $demies[0]['match_equipe_A']=$resultattb[0]['equipe_id'];
          $demies[0]['match_equipe_B']=$resultattb[3]['equipe_id'];
          $demiesOk=false;
          
          if($poolFinie){
            updateMatchTeams($demies[0]['match_id'], $demies[0]['match_equipe_A'], $demies[0]['match_equipe_B']);
          }
      }

      if((empty($demies[1]) || $demies[1]['teamA']==0) && !empty($resultattb[1]) && !empty($resultattb[2]) ){
          $demies[1]['match_equipe_A']=$resultattb[1]['equipe_id'];
          $demies[1]['match_equipe_B']=$resultattb[2]['equipe_id'];
          $demiesOk=false;
          if($poolFinie){
            updateMatchTeams($demies[1]['match_id'], $demies[1]['match_equipe_A'], $demies[1]['match_equipe_B']);
          }
      }
      
      if((empty($demies[2]) || $demies[2]['teamA']==0)){ // finale
        
        // On a pas encore de teamA
        if($demiesOk){
          // Mais les demis sont OK
          $equipe_A = $demies[0]['match_score_A']>$demies[0]['match_score_B'] ? $demies[0]['match_equipe_A'] : $demies[0]['match_equipe_B'];
          $equipe_B = $demies[1]['match_score_A']>$demies[1]['match_score_B'] ? $demies[1]['match_equipe_A'] : $demies[1]['match_equipe_B'];
          updateMatchTeams($demies[2]['match_id'],$equipe_A,$equipe_B);
        }
        // Pas de finale
        $sql=sprintf("select t_m.match_id,t_m.match_date,t_m.match_equipe_A,t_m.match_equipe_B,t_m.match_score_A,t_m.match_score_B
        from t_matchs as t_m
        inner join t_saisons as t_s on t_s.saison_id=t_m.match_saison_id
        where t_s.saison_id='%d' and t_m.match_type_id in (6)
        group by t_m.match_id order by t_m.match_type_id,t_m.match_date",$saison->saison_id);	
        
        $demiesTmp = $db->SelectAll($sql);
        
        if(count($demiesTmp)>0){
          $demies[2] = $demiesTmp[0];
        }
        
      }
      
      $ret = new stdClass();
      
      $ret->scores      = $resultattb;
      $ret->demies      = $demies;
      $ret->warn        = $warn;
      $ret->matchs      = $matchsParDate;
      $ret->equipes     = $equipes;
      $ret->demiesOk    = $demiesOk;

      return $ret;
      
    }
    
    public static function getRankingLayout($saison_id,$type,$pars=array()){
      
      if(is_null($pars)) $pars = array();
      
      $smarty = commun::getSmartyPartial();
      
      $ret = self::getRanking($saison_id, $type);
      
      $params = array(
         'scores'           =>  $ret->scores
        ,'demies'           =>  $ret->demies
        ,'warn'             =>  $ret->warn
        ,'demiesOk'         =>  $ret->demiesOk
        ,'matchs'           =>  $ret->matchs
        ,'equipes'          =>  $ret->equipes
        ,'render'           =>  array(
             'complet'      =>  false
            ,'classement'   =>  true
            ,'demies'       =>  ($type==saison::CHAMPIONNAT ? true : false)
            ,'matchs'       =>  true
        )        
      );
      
      $params = array_merge($params,$pars);
      
      $smarty->assign($params);
      
      $layout = $smarty->fetch("ranking.".TPL_EXT);
      
      return $layout;
      
    }
   
    public static function renderRankingLayout($saison_id,$type,$pars=array()){
      $ret = self::getRankingLayout($saison_id, $type,$pars);
      echo $ret;
    }
    
    /**
     *
     * @param int $saison_id
     * @param string $compet_id
     * @return StdClass 
     */
    public static function getCalendar($saison_id=null,$type,$pars=array()){
      
      if(!isset($saison_id) || $saison_id==0) $saison_id = saison::getCurrentId ();
      
      $db           = parent::getDb();
      $saison       = saison::getSaison($saison_id);
      $where        = array();
      
      switch($type){
        case saison::CHAMPIONNAT:
          $compet_id =  '1,3'; 
          break;
        case saison::JOUTELIBRE:
          $compet_id =  '4'; 
          break;
      }
      
      if($saison_id!=0){
        $where[]      = sprintf('match_saison_id = %d',$saison_id);
      }
      if($compet_id!=0){
        $where[]      = sprintf('match_compet_id in (%s)',$compet_id);
      }
      
      if(count($where)>0){
        $where =  'where '.  implode(' AND ', $where);
      }
      
      $orderBy  = '';
      $limit    = '';
      
      if(is_array($pars)){
        if(isset($pars['where']) && !is_null($pars['where'])){
          
          if(strpos(strtolower($where),'where')===FALSE){
            if(strpos(strtolower($pars['where']),'where')===FALSE){
              $where = 'WHERE ';
            }
          }
          
          $where = $where .' '.$pars['where'];
        }
        
        if(isset($pars['order']) && !is_null($pars['order'])){
          $orderBy = $orderBy .' '.$pars['order'];
        } else {
					$orderBy = 'match_id';
				}
        
        if(!empty($pars['limit'])){
          $limit = 'LIMIT '.$pars['limit'];
        }
      }
      
      if(!is_null($orderBy) && strlen($orderBy)>0){
        $orderBy=" ORDER BY $orderBy";
      }
      
      
      
      
      $sql          = sprintf('select * from t_matchs %s', $where);
      $ret          = new StdClass();
      
      $sql1         = $sql." $orderBy $limit";
      
      $matchs       = array();
      
      foreach($db->SelectAll($sql1) as $match){
        $matchs[] = new match($match);
      }
      
      $ret->matchs  = $matchs;
      
      $sql1         = $sql." group by match_lieu_id $limit";
      
      $ret->lieux   = $db->SelectCol($sql1, 'match_lieu_id');
      
      $sql1         = $sql." group by match_compet_id $limit";
      $ret->compets = $db->SelectCol($sql1, 'match_compet_id');
      
      $sql1         = $sql." group by match_type_id $limit";
      $ret->types   = $db->SelectCol($sql1, 'match_type_id');
      
      return $ret;
      
    }
    
    /**
     * 
     * @param int $saison_id
     * @param char $type
     * @param array $pars
     * @return stdObject
     */
    public static function getComingDates($saison_id=null,$type=null,$pars=array()){
      if(is_null($saison_id)) $saison_id = saison::getCurrentId ();
      if(is_null($type))      $type = saison::CHAMPIONNAT;
      
      $default = array('order'=>'match_date','where'=>'AND match_date >= NOW()');
      $p = array_merge($pars,$default); 
      
      $cal  = self::getCalendar($saison_id,$type,$p);
      
      return $cal;
    }

    public static function getComingDatesLayout($saison_id=null,$type=null,$limit=3,$pars=array()){
      return '';
    }

    public static function getCalendarLayout($saison_id,$type,$pars=array()){
      
      if(is_null($pars)) $pars = array();
      
      $smarty = commun::getSmartyPartial();
      
      $ret = self::getCalendar($saison_id, $type);
      
      $params = array(
           'matchs'   => $ret->matchs
          ,'lieux'    => $ret->lieux
          ,'compets'  => $ret->compets
      );
      
      $params = array_merge($params,$pars);
      
      $smarty->assign($params);
      
      $layout = $smarty->fetch("calendar.".TPL_EXT);
      
      return $layout;
      
    }
    
    public static function getCompetLib($id,$diminutif=false){
      $db = parent::getDb();
      $sql = sprintf('select * from t_compets where compet_id=%d',$id);
      $row = $db->SelectFirst($sql);
      
      $lib = (!$diminutif || empty($row['compet_lib']) ? $row['compet_lib'] : $row['compet_diminutif']);
      return $lib;
    }
    
    public function competLib($diminutif=false){
      return self::getCompetLib($this->match_compet_id,$diminutif);
    }

    public static function getMatchLib($id=null,match $match=null, $link=true){
      
      if(is_null($match) && !is_null($id)){
        $match = self::getMatch($id);
      }
      $ret[] = '<span class="loli-match-lib">';
      if(!empty($match->match_equipe_A) && !empty($match->match_equipe_B)){
        $void = new stdClass();
        require_once(PATH_LIB .'smarty/plugins/function.equipe_link.php');
        $ret[] =  '<span class="equipe-a '.($match->match_score_A>$match->match_score_B ? 'winner':'').'">';
        $ret[] = smarty_function_equipe_link(array('id'=>$match->match_equipe_A,'link'=>$link), $void);
        $ret[] =  '</span>';
        $ret[] = '<span class="vs">vs</span>';
        $ret[] =  '<span class="equipe-b '.($match->match_score_A<$match->match_score_B ? 'winner':'').'">';
        $ret[] = smarty_function_equipe_link(array('id'=>$match->match_equipe_B,'link'=>$link), $void);
        $ret[] = '</span>';
        
        
      } else if(!empty($match->match_type_lib)){
        $ret[] = $match->match_type_lib;
      } else if(!empty($match->match_type_id)){
        $db = self::getDb();
        $sql=sprintf("select match_type_lib from t_matchs_type where match_type_id='%d'",$match->match_type_id);
        $sql = $db->SelectFirstCol($sql, "match_type_lib");
        $ret[] = $sql;//
      }
      
      $ret[] = '</span>';
      
      return join('',$ret);
    }
    
    public function matchLib($link=true){
      
      $ret = self::getMatchLib(null, $this, $link);
      
      return $ret;
    }
    
    public static function getMatchLibText($id=null,match $match=null){
      if(is_null($match) && !is_null($id)){
        $match = self::getMatch($id);
      }
      $link     = false;
      $ret[]    = '';
      if(!empty($match->match_equipe_A) && !empty($match->match_equipe_B)){
        $void   = new stdClass();
        $lib    = smarty_function_equipe_link(array('id'=>$match->match_equipe_A,'link'=>$link), $void);
        $lib    = strip_tags($lib);
        $ret[]  = $lib;
        $ret[]  = ' vs ';
        $lib    = smarty_function_equipe_link(array('id'=>$match->match_equipe_B,'link'=>$link), $void);
        $lib    = strip_tags($lib);
        $ret[]  = $lib;
        
      } else if(!empty($match->match_type_lib)){
        $ret[] = $match->match_type_lib;
      }
      
      return join('',$ret);
    }
    
    public function matchLibText(){
      
      $ret = self::getMatchLibText(null, $this);
      
      return $ret;
      
    }
    
    public static function getMatch($match_id){
      /* @var $db DataBase */
      $db = self::getDb();
      
      $sql = sprintf("select * from t_matchs where match_id = %d",$match_id);
      
      $match = $db->selectFirst($sql);
      
      $match = new match($match);
      
      return $match;
      
    }

    public static function getMatchs(){
      /* @var $db DataBase */
      $db = self::getDb();
      
      $sql = sprintf("select * from t_matchs");
      
      $matchs = $db->SelectAllByToObject($sql,'match_id',self::getClassName());
      
      return $matchs;
      
    }
    
    public static function getMatchScore($id=null, match $match=null,$equipe_lib=false){
      
      if(is_null($match) && !is_null($match)){
        $match =  self::getMatch($id);
      }
      $ret='';
      if($match){
        $void = new stdClass();
        require_once(PATH_LIB .'smarty/plugins/function.score.php');
        $params = array(
             'scoreA'   =>  $match->match_score_A
            ,'scoreB'   =>  $match->match_score_B
            ,'match_id' =>  $match->match_id
        );
        
        if($equipe_lib){
          $params = array_merge($params,array(
               'equipeA'=>$match->match_equipe_A
              ,'equipeB'=>$match->match_equipe_B
            ));
        }
        $ret = smarty_function_score($params, $void);
        
      }
      return $ret;
    }
    public function matchScore($equipe_lib=false){
      return self::getMatchScore(null,$this,$equipe_lib);
    }
    
    public static function updateScore($match_id,$score_A,$score_B){
      
      $match = self::getMatch($match_id);
      $ret=0;
      
      $score_A = is_numeric($score_A) ? $score_A : 0;
      $score_B = is_numeric($score_B) ? $score_B : 0;
      
      if($match && is_numeric($score_A) && is_numeric($score_B)){
        $sql=sprintf("Update %s set match_score_A=%d, match_score_B=%d where match_id=%d",self::getTableName(),$score_A,$score_B,$match_id);
        $db = self::getDb();
        $db->Update($sql);
      }
      
      return $ret;
    }
    
    public static function getMatchsBySaison($saison_id=0,$groupBy='match_id',$orderBy='match_id'){
      $db = self::getDb();
      
      $where = array();
      
      $sql = "select * from t_matchs"; // as t_m inner join t_liens_es on(match_id)";
      
      if(isset($saison_id) && is_numeric($saison_id) && $saison_id > 0){
        $where[]="match_saison_id='$saison_id'";        
      }
      
      if(count($where)>0){
        $sql = sprintf("$sql where %s",  join('AND', $where));
      }
      
      if(isset($orderBy) && !empty($orderBy)){
        $sql = sprintf("$sql order by %s",$orderBy);                
      }
      
      $ret = $db->SelectAllByToObject($sql, $groupBy,self::getClassName());
      
      return $ret;
    }
    
    public function getRealImagesCount(){
      $ret = false;
      $obj = image::getMatchImages($this);
      $ret    = count($obj->images);
      return $ret;
    }
    
    public function hasRealImages(){
      $cnt = $this->getImagesCount();
      return ($cnt>0);
    }

    public function getImagesCount(){
      $ret = false;
      $ret = $this->match_has_image;
      return $ret;
    }
    
    public function hasImages(){
      $cnt = $this->getImagesCount();
      return ($cnt>0);
    }

    public function getImages(){
      $obj = image::getMatchImages($this);
      return $obj;
    }
    
    public static function uploadMatchImagesCnt($match){
      $ret=false;
      
      if(!$match instanceof match && is_numeric($match)){
        $match = self::getMatch($match);
      }
      
      if($match){
        $av = $match->match_has_image;
        $cnt = $match->getRealImagesCount();
        if($av!=$match->match_has_image){
         $st = true;
        }
      }
      
      return $st;
    }
    
    public static function uploadMatchImages(){
      $upload = new myUploadHandler();
      
      if(isset($_POST['id']) && $_POST['id']!=0){
        $match = self::getMatch($_POST['id']);
        if($match){
          $cnt = $match->getRealImagesCount();
        }
      }
      
    }
    
    public function updateHasImage($cnt){
      if($this->match_has_image!=$cnt){
        $this->match_has_image = $cnt;
        $db = self::getDb();
        $this->update(array('match_has_image'=>$this->match_has_image),self::getClassName());
      }      
      return $this;
    }
    
}

